package org.ilovecode.mvc
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class View extends Sprite implements IView
	{
		protected var _constructed:Boolean;
		protected var model:IModel;
		protected var controller:IController;
		protected var _name:String;
		
		public function View(name:String = "")
		{
			super();
			
			if (name != "")
				this._name = name;
			
			model = Model.getInstance();
			controller = Controller.getInstance();
			
			(this.stage != null) ? init() : this.addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(event:Event = null):void
		{
			if (this.hasEventListener(Event.ADDED_TO_STAGE)) 
				this.removeEventListener(Event.ADDED_TO_STAGE, init);
			
			this.addEventListener(Event.REMOVED_FROM_STAGE, destroy);
			if (!_constructed) 
			{
				construct();
				_constructed = true;
			}
			initText();
			initUI();
			addListeners();
		}
		
		// --- Construction --------------------------------
		
		protected function construct():void
		{
		}
		
		protected function initUI():void
		{
		}
		
		protected function initText():void
		{
		}
		
		protected function addListeners():void
		{
		}
		
		// --- Destruction ---------------------------------
		
		private function destroy(event:Event):void
		{
			this.removeEventListener(Event.REMOVED_FROM_STAGE, destroy);
			this.addEventListener(Event.ADDED_TO_STAGE, init);
			removeListeners();
			removeUI();
			removeText();
		}
		
		protected function removeListeners():void
		{
		}
		
		protected function removeUI():void
		{
		}
		
		protected function removeText():void
		{
		}
		
		protected function update(event:Event):void
		{
			
		}
	}
}